from pyppeteer import launch
import asyncio


def screen_size():
    '''使用tkinter获取屏幕大小'''
    import tkinter
    tk = tkinter.Tk()
    width = tk.winfo_screenwidth()
    height = tk.winfo_screenheight()
    tk.quit()
    return width,height

async def login():
    browser = await launch(headless=False)
    js1 = '''() =>{
            Object.defineProperties(navigator,{
            webdriver:{
                get: () => undefined
                }
            })
        }'''
    js2 = '''() => {
                window.navigator.webdriver
        }'''
    page = await browser.newPage()
    await page.setUserAgent(userAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36')
    login_url = 'https://login.taobao.com/member/login.jhtml?from=taobaoindex&f=top&style=&sub=true&redirect_url=https%3A%2F%2Fi.taobao.com%2Fmy_taobao.htm%3Fspm%3Da21bo.2017.1997525045.1.5af911d9D0pg1t'
    await page.goto(url=login_url)
    width, height = screen_size()
    await page.setViewport({'width': width, 'height': height})
    await page.evaluate(js1)
    await page.evaluate(js2)
    qie = await page.xpath('//*[@id="J_Quick2Static"]')  #切换成账号登录界面
    await qie[0].click()
    await asyncio.sleep(2)
    user = await page.xpath('//*[@id="TPL_username_1"]')  #输入账号
    await user[0].type(username)
    password = await page.xpath('//*[@id="TPL_password_1"]')  #输入密码
    await password[0].type(pwd)
    button = await page.xpath('//*[@id="TPL_password_1"]')  #点击登录
    await button[0].click()
    await asyncio.sleep(2)
    if page.url == login_url:
        print('需要验证!')
        slider=await page.xpath('//*[@id="nc_1__scale_text"]/span')
        size = await slider[0].boundingBox()
        await page.mouse.move(list(size.values())[0],list(size.values())[1])
        await page.mouse.down()
        await page.mouse.move(10000, list(size.values())[1],options={'steps':10})
        await page.mouse.up()
        button = await page.xpath('//*[@id="J_SubmitStatic"]')  # 点击登录
        await button[0].click()
    await asyncio.sleep(100)
    await browser.close()


if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(login())



